package com.coocaa.treasure.view.picture;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.ImageView;

import com.coocaa.treasure.util.Constants;
import com.coocaa.treasure.widget.BaseView;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by xfk on 2015/9/8.
 */
public class PictureItemView extends ImageView{
    private String imageUrl;
    private Context mContext;
    public PictureItemView(Context context) {
        super(context);
        mContext = context;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
        loadImage(imageUrl);
        int tag = (Integer)(this.getTag());
//        if(tag == 0) {
//            checkViewIsShow();
//        }
    }

    private void checkViewIsShow() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Log.i("0909", "checkViewIsShow: "+isShowOnWindow());
                    if(isShowOnWindow()) {
                        return;
                    }
                }
            }
        }).start();
    }
    private boolean isShowOnWindow() {
        int[] to = new int[2];
        to[0] = 0;
        to[1] = 0;
        getLocationInWindow(to);

        Log.i("0909", "to 0: "+to[0]);
        if(to[0] > 0 || to[1] > 0) {
            return true;
        }

        return false;
    }

    Handler uiHandler = new Handler(Looper.getMainLooper());
    private void loadImage(final String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap image = null;
                Log.i("0908", "loadImage + ");
                String temp = "demo_resource/picture/"+url;
                AssetManager am = mContext.getResources().getAssets();
                try
                {
                    BitmapFactory.Options opt = new BitmapFactory.Options();
                    opt.inJustDecodeBounds = true;
                    InputStream is = am.open(temp);
                    BitmapFactory.decodeStream(is, null, opt);
                    opt.inSampleSize = 1;
                    int picWidth  = opt.outWidth;
                    int picHeight = opt.outHeight;
                    Log.i("0909", "picWidth: "+picWidth+", picHeight: "+picHeight);
                    if(picWidth > picHeight){
                        if(picWidth > Constants.Div(534))
                            opt.inSampleSize = picWidth/Constants.Div(534);
                    } else{
                        if(picHeight > Constants.Div(316))
                            opt.inSampleSize = picHeight/Constants.Div(316);
                    };
                    opt.inJustDecodeBounds = false;
                    image = BitmapFactory.decodeStream(is, null, opt);
                    is.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }

                final Bitmap finalImage = resizeImage(image, Constants.Div(534), Constants.Div(316));
                uiHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (finalImage != null) {
                            setImageBitmap(getRoundedCornerBitmap(finalImage));
                            setBackgroundDrawable(null);
                        } else {
                            Log.i("0908", "Image is null");
                        }
                    }
                });

                if(image != null && !image.isRecycled())
                image.recycle();
            }
        }).start();
    }

    private Bitmap getRoundedCornerBitmap(Bitmap bitmap) {

        if (bitmap == null)
            return null;

        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas roundCanvas = new Canvas(output);
        roundCanvas.setBitmap(output);
        int color = 0xff424242;
        Paint paint = new Paint();
        Rect rect = new Rect(0, 0,
                bitmap.getWidth(), bitmap.getHeight());
        RectF rectF = new RectF(rect);
        float roundPx = 12;
        paint.setAntiAlias(true);

        roundCanvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        roundCanvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

        roundCanvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }
    //使用Bitmap加Matrix来缩放
    public static Bitmap resizeImage(Bitmap bitmap, int w, int h)
    {
        if(bitmap == null)
            return null;
        Bitmap BitmapOrg = bitmap;
        int width = BitmapOrg.getWidth();
        int height = BitmapOrg.getHeight();
        int newWidth = w;
        int newHeight = h;

        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // if you want to rotate the Bitmap
        // matrix.postRotate(45);
        Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
                height, matrix, true);
        return resizedBitmap;
    }


}
